from PySide6.QtCore import Signal, QThread
from ...base import ThreadBase
from tools import ImageConversion
from traceback import format_exc


class ImageConversionThread(ThreadBase):
    progress = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.files = None
        self.from_t = None
        self.to_t = None
        self.save_file = None
        self.size = None

    def run(self):
        file_len = len(self.files)
        for index, file in enumerate(self.files):
            self.progress.emit(f'正在进行图片转换，进度：{index + 1} / {file_len}，请稍后...')
            try:
                image = ImageConversion(file, self.save_file)
                if self.to_t == 'svg':
                    getattr(image, self.to_t, None)(self.size)
                else:
                    getattr(image, self.to_t, None)()
            except Exception as e:
                error = format_exc()
                print(error)
                self.error.emit(error)

    def set_value(self, from_t: str, to_t: str, files: str, save_file: str, size: str, *args, **kwargs):
        self.from_t = from_t.lower()
        self.to_t = to_t.lower()
        self.files = files
        self.save_file = save_file
        self.size = set(size.split('x'))
